<template>
  <div class="container">
    <h1>ComfyUI 工作流展示</h1>
    
    <!-- 导入区域 -->
    <div class="import-section">
      <div class="file-drop-zone" 
           @dragover.prevent 
           @drop.prevent="handleFileDrop"
           :class="{ 'dragging': isDragging }"
           @dragenter.prevent="isDragging = true"
           @dragleave.prevent="isDragging = false">
        <input 
          type="file" 
          ref="fileInput" 
          accept=".json"
          @change="handleFileSelect" 
          style="display: none"
        >
        <div class="drop-zone-content">
          <i class="upload-icon">📁</i>
          <p>拖拽 JSON 文件到此处或 <button @click="$refs.fileInput.click()" class="btn-link">点击选择文件</button></p>
        </div>
      </div>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar" v-if="workflowData">
      <div class="search-box">
        <input 
          v-model="searchQuery" 
          type="text" 
          placeholder="搜索节点..."
        >
      </div>
      <div class="actions">
        <button @click="exportWorkflow" class="btn">导出工作流</button>
        <button @click="showConnections = !showConnections" class="btn">
          {{ showConnections ? '隐藏连接' : '显示连接' }}
        </button>
        <button @click="toggleView" class="btn">
          {{ isJsonView ? '切换到卡片视图' : '切换到JSON视图' }}
        </button>
        <button @click="toggleAllNodes" class="btn">
          {{ allNodesHidden ? '显示所有节点' : '隐藏所有节点' }}
        </button>
        <button @click="generateComponent" class="btn generate-btn">
          <span class="btn-icon">⚡</span> 生成组件
        </button>
        <button v-if="isCanvasView" 
                @click="backToNormalView" 
                class="btn back-btn">
          返回普通视图
        </button>
      </div>
    </div>

    <!-- 节点控制面板 -->
    <div v-if="workflowData && !isJsonView" class="node-controls">
      <div v-for="(node, id) in workflowData" 
           :key="id" 
           class="node-control-item">
        <span class="node-title">{{ node._meta?.title || `Node ${id}` }}</span>
        <button 
          @click="toggleNodeVisibility(id)"
          class="btn-toggle"
          :class="{ 'hidden': node.show === false }"
        >
          {{ node.show === false ? '显示' : '隐藏' }}
        </button>
      </div>
    </div>

    <!-- JSON 预览 -->
    <div v-if="workflowData && isJsonView" class="json-preview">
      <json-viewer 
        :value="workflowData" 
        :expand-depth="2" 
        boxed 
        sort 
        copyable
      ></json-viewer>
    </div>

    <!-- 节点视图 -->
    <div v-else-if="workflowData" 
         class="workflow-view"
         :class="{ 'canvas-view': isCanvasView }">
      <JsonNodeViewer 
        v-if="!isCanvasView"
        :jsonData="workflowData"
        :showConnections="showConnections"
      />
      <WorkflowCanvas 
        v-else
        :nodes="workflowData"
      />
    </div>

    <!-- 空状态提示 -->
    <div v-else class="empty-state">
      <p>请导入 ComfyUI 工作流 JSON 文件开始查看</p>
    </div>

    <!-- 添加组件生成对话框 -->
    <div v-if="showGenerateDialog" class="generate-dialog">
      <div class="dialog-content">
        <h3>组件生成器</h3>
        <div class="component-options">
          <div class="option-group">
            <label>组件名称:</label>
            <input v-model="componentName" placeholder="输入组件名称" />
          </div>
          <!-- <div class="option-group">
               <label>选择模板:</label>
            <select v-model="selectedTemplate">
              <option value="CLIPTextEncode">CLIP Text Encode</option>
              <option value="CheckpointLoaderSimple">Checkpoint Loader</option>
              <option value="KSampler">KSampler</option>
              <option value="LoadImage">Load Image</option>
              <option value="SaveImage">Save Image</option>
              <option value="VAEDecode">VAE Decode</option>
              <option value="VAEEncode">VAE Encode</option>
            </select> 
          </div> -->
        </div>
        <div class="dialog-actions">
          <button @click="confirmGenerate" class="btn">确认生成</button>
          <button @click="showGenerateDialog = false" class="btn btn-secondary">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import JsonViewer from 'vue-json-viewer'
import JsonNodeViewer from './components/JsonNodeViewer.vue'
import WorkflowCanvas from './components/WorkflowCanvas.vue'
import 'vue-json-viewer/style.css'

const workflowData = ref(null)
const searchQuery = ref('')
const isDragging = ref(false)
const isJsonView = ref(false)
const showConnections = ref(false)
const isCanvasView = ref(false)

// 组件生成相关的状态
const showGenerateDialog = ref(false)
const componentName = ref('')
const selectedTemplate = ref('KSampler')

// 文件处理
const handleFileDrop = (event) => {
  isDragging.value = false
  const file = event.dataTransfer.files[0]
  if (file) {
    loadJsonFile(file)
  }
}

const handleFileSelect = (event) => {
  const file = event.target.files[0]
  if (file) {
    loadJsonFile(file)
  }
}

const loadJsonFile = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      const json = JSON.parse(e.target.result)
      workflowData.value = json
    } catch (error) {
      alert('无效的 JSON 文件格式')
    }
  }
  reader.readAsText(file)
}

// 导出功能
const exportWorkflow = () => {
  if (!workflowData.value) return
  
  const dataStr = JSON.stringify(workflowData.value, null, 2)
  const dataBlob = new Blob([dataStr], { type: 'application/json' })
  const url = URL.createObjectURL(dataBlob)
  const link = document.createElement('a')
  link.href = url
  link.download = 'workflow.json'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)
}

// 视图切换
const toggleView = () => {
  isJsonView.value = !isJsonView.value
}

// 修改生成组件的处理函数
const generateComponent = () => {
  // 先显示对话框
  showGenerateDialog.value = true
}

// 修改确认生成组件的函数
const confirmGenerate = async () => {
  if (!componentName.value) {
    alert('请输入组件名称')
    return
  }

  try {
    // 保持原有的数据结构，只切换视图
    if (workflowData.value) {
      // 切换到 Canvas 视图
      isCanvasView.value = true
      // 关闭对话框
      showGenerateDialog.value = false
    } else {
      throw new Error('没有可用的工作流数据')
    }
  } catch (error) {
    console.error('生成组件失败:', error)
    alert('生成组件失败，请重试')
  }
}

// 添加返回到普通视图的功能
const backToNormalView = () => {
  isCanvasView.value = false
}

// 获取示例输入数据
const getSampleInputs = (type) => {
  const samples = {
    KSampler: {
      seed: 91905811412295,
      steps: 20,
      cfg: 8,
      sampler_name: "dpmpp_2m",
      model: ["14", 0],
      positive: ["6", 0],
      negative: ["7", 0]
    },
    CLIPTextEncode: {
      text: "示例提示词",
      clip: ["14", 1]
    },
    CheckpointLoaderSimple: {
      ckpt_name: "v1-5-pruned.ckpt"
    },
    LoadImage: {
      image: "example.png"
    },
    SaveImage: {
      filename_prefix: "output",
      images: ["5", 0]
    },
    VAEDecode: {
      samples: ["3", 0],
      vae: ["14", 2]
    },
    VAEEncode: {
      pixels: ["10", 0],
      vae: ["14", 2]
    }
  }
  return samples[type] || {}
}

// 添加节点显示控制相关的计算属性和方法
const allNodesHidden = computed(() => {
  if (!workflowData.value) return false
  return Object.values(workflowData.value).every(node => node.show === false)
})

// 切换单个节点的显示状态
const toggleNodeVisibility = (nodeId) => {
  if (!workflowData.value || !workflowData.value[nodeId]) return
  
  workflowData.value[nodeId] = {
    ...workflowData.value[nodeId],
    show: workflowData.value[nodeId].show === false ? true : false
  }
}

// 切换所有节点的显示状态
const toggleAllNodes = () => {
  if (!workflowData.value) return
  
  const newShowState = allNodesHidden.value
  Object.keys(workflowData.value).forEach(nodeId => {
    workflowData.value[nodeId] = {
      ...workflowData.value[nodeId],
      show: newShowState
    }
  })
}
</script>

<style scoped>
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.workflow-view {
  background: #f5f5f5;
  border-radius: 8px;
  min-height: 200px;
}

.import-section {
  margin-bottom: 30px;
}

.file-drop-zone {
  border: 2px dashed #ddd;
  border-radius: 8px;
  padding: 40px;
  text-align: center;
  background: #f8f9fa;
  transition: all 0.3s ease;
}

.file-drop-zone.dragging {
  background: #e9ecef;
  border-color: #42b883;
}

.drop-zone-content {
  color: #666;
}

.upload-icon {
  font-size: 48px;
  margin-bottom: 10px;
}

.btn-link {
  background: none;
  border: none;
  color: #42b883;
  cursor: pointer;
  text-decoration: underline;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  gap: 20px;
}

.search-box input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 300px;
}

.btn {
  padding: 8px 16px;
  background: #42b883;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.btn:hover {
  background: #3aa876;
}

.generate-btn {
  display: flex;
  align-items: center;
  gap: 8px;
}

.btn-icon {
  font-size: 16px;
}

.generate-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-content {
  background: white;
  padding: 24px;
  border-radius: 8px;
  min-width: 400px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.component-options {
  margin: 20px 0;
}

.option-group {
  margin-bottom: 16px;
}

.option-group label {
  display: block;
  margin-bottom: 8px;
  color: #666;
}

.option-group input,
.option-group select {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.dialog-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}

.btn-secondary {
  background: #666;
}

.json-preview {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.empty-state {
  text-align: center;
  color: #666;
  margin-top: 40px;
}

@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
  }
  
  .search-box input {
    width: 100%;
  }
}

/* Canvas 视图的样式 */
.workflow-view.canvas-view {
  background: #ffffff;
  height: 800px;  /* 固定高度 */
  overflow: hidden;
  display: flex;
  border: 1px solid #eee;
  border-radius: 8px;
}

.back-btn {
  background: #666;
}

.back-btn:hover {
  background: #555;
}

.node-controls {
  margin: 20px 0;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #eee;
}

.node-control-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px;
  border-bottom: 1px solid #eee;
}

.node-control-item:last-child {
  border-bottom: none;
}

.node-title {
  font-size: 14px;
  color: #333;
}

.btn-toggle {
  padding: 4px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  background: #42b883;
  color: white;
  font-size: 12px;
  transition: all 0.3s ease;
}

.btn-toggle.hidden {
  background: #666;
}

.btn-toggle:hover {
  opacity: 0.9;
}

/* 确保工具栏按钮样式统一 */
.toolbar .btn {
  margin-left: 8px;
}

.toolbar .btn:first-child {
  margin-left: 0;
}
</style>